import random
import time

from celery import Celery
from flask import Flask
from flask_bcrypt import Bcrypt
from flask_jwt import JWT
from flask_restful import Resource, Api
from flask_uploads import UploadSet, IMAGES, configure_uploads
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from common.crawlUtil import crawl
from common.db import User, Base, KeywordData, UrlList
from default_config import TYPE_PRICE
from resources.manage_api import AddKeyword, Refresh, GetUrl, UploadImage, UpdateUrl, DeleteUrl, DeleteKeyword
from resources.proxy import Proxy
from resources.user_api import Taobao, Register, KeywordList
from resources.wechat_api import Wechat, WechatMenu
from resources.weidian_api import update_price

app = Flask(__name__)
app.config.from_pyfile('default_config.py')
api = Api(app)
bcrypt = Bcrypt(app)

photos = UploadSet('IMAGES', IMAGES)
configure_uploads(app, photos)

accessKey = app.config["QINIU_ACCESSKEY"]
secretKey = app.config["QINIU_SECRET_KEY"]

engine = create_engine("mysql+pymysql://root:" + app.config['MYSQL_PASSWORD'] + "@localhost:3306/tandi?charset=utf8",
                       isolation_level="READ UNCOMMITTED")
Session = sessionmaker(bind=engine)
session = Session()

Base.metadata.create_all(engine)

celery = Celery(app.name, backend=app.config['CELERY_RESULT_BACKEND'], broker=app.config['CELERY_BROKER_URL'])
celery.conf.update(app.config)


def authenticate(username, password):
    user = session.query(User).filter_by(username=username).first()
    if not user or not user.verify_password(password):
        return None
    user.last_login_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    session.add(user)
    session.commit()
    return user


def identity(payload):
    user_id = payload['identity']
    return session.query(User).filter_by(id=user_id).first()


jwt = JWT(app, authenticate, identity)


def to_dict(self):
    return {c.name: getattr(self, c.name, None) for c in self.__table__.columns}


Base.to_dict = to_dict


class Tandi(Resource):
    @staticmethod
    def get():
        return {"Hello": "Tandi"}


@celery.task()
def calculate():
    from run import session
    urlLists = session.query(UrlList).all()
    crawl(urlLists)
    keywords = session.query(KeywordData).all()
    for key in keywords:
        urlLists = session.query(UrlList).filter_by(type=TYPE_PRICE, keyword=key.keyword, is_valid=True).all()
        sum_price = 0
        sum_sales = 0
        for url in urlLists:
            sum_price += url.product_price * url.product_sales
            sum_sales += url.product_sales
        key.average_price = sum_price / sum_sales
        ran1 = (random.randint(0, 20) - 10) / 1000
        ran2 = (random.randint(0, 20) - 10) / 1000
        key.tmp_average_price = key.average_price * (1 + ran1)
        key.tmp_average_origin_price = key.average_origin_price * (1 + ran2)
        key.tandi_price = round(key.tmp_average_origin_price * (1 + key.profit), 2)
        session.add(key)
        try:
            session.commit()
            update_price(key.purchase_url.split('=')[1], key.tandi_price)
        except:
            session.rollback()


@app.after_request
def after_request(response):
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization,enctype')
    response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
    return response


api.add_resource(Tandi, '/')
api.add_resource(Taobao, '/search')
api.add_resource(Proxy, '/proxy')
api.add_resource(KeywordList, '/keywordList')
api.add_resource(Register, '/register')
api.add_resource(AddKeyword, '/addkey')
api.add_resource(DeleteKeyword, '/deleteKey')
api.add_resource(Refresh, '/refresh')
api.add_resource(GetUrl, '/geturl')
api.add_resource(UpdateUrl, '/updateUrl')
api.add_resource(DeleteUrl, '/deleteUrl')
api.add_resource(UploadImage, '/uploadImg')
api.add_resource(Wechat, '/wechat')
api.add_resource(WechatMenu, '/wechatmenu')

if __name__ == '__main__':
    app.run(debug=app.config['DEBUG'], port=app.config['PORT'], host=app.config['HOST'])
